<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品参数</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <el-alert title="注意只能为三级分类设定参数" type="warning" effect="light" show-icon closable></el-alert>
      <el-row :gutter="20" style="margin:20px">
        <el-col :span="3">
          选择商品分类
        </el-col>
        <el-col :span="21">
          <!-- 级联 -->
          <el-cascader @change="handleChange" clearable v-model="selectedKeys" :options="cateList"
            :props="{ expandTrigger: 'hover',label:'cat_name',value:'cat_id'}"></el-cascader>
        </el-col>
      </el-row>

      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <el-tab-pane label="动态属性" name="many">
          <el-button type="primary" :disabled="isBtnOk" @click="addDialogVisible = true">添加动态参数</el-button>
          <!-- 渲染表格 -->
          <el-table :data="manyTableData">
            <el-table-column type="expand" label="展开">
              <!-- 渲染循环tag -->
              <template v-slot="{row}">
                <el-tag @close="handleRemove(row,index)" style="margin-left:4px" v-for="(item,index) in row.attr_vals"
                  :key="index" closable>{{item}}
                </el-tag>
                <el-input class="input-new-tag" v-if="row.inputVisible" v-model.trim="row.inputValue" ref="saveTagInput"
                  size="small" @keyup.enter.native="handleInputConfirm(row)" @blur="handleInputConfirm(row)">
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template v-slot="{row}">
                <el-button type="primary" size="mini" icon="el-icon-edit" @click="showEditDialog(row)"></el-button>
                <el-button type="primary" size="danger" icon="el-icon-delete" @click="removeBox(row.attr_id)">
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button type="primary" :disabled="isBtnOk" @click="addDialogVisible = true">添加静态属性</el-button>
          <!-- 渲染表格 -->
          <el-table :data="onlyTableData">
            <el-table-column type="expand"></el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column label="参数名称"></el-table-column>
            <el-table-column label="操作">
              <template v-slot="{row}">
                <el-button type="primary" size="mini" icon="el-icon-edit" @click="showEditDialog(row)"></el-button>
                <el-button type="primary" size="danger" icon="el-icon-delete" @click="removeBox(row.attr_id)">
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加属性弹出对话框 -->
    <el-dialog :title="'添加'+dialogText" :visible.sync="addDialogVisible" width="30%">
      <el-form ref="addFormRef" label-width="80px" :model="addForm" :rules="addFormRules">
        <el-form-item :label="dialogText" prop="attr_name">
          <el-input v-model="addForm.attr_name">
          </el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCate">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改的对话框 -->
    <el-dialog :title="'修改'+dialogText" :visible.sync="editDialogVisible" width="30%">
      <el-form ref="editFormRef" label-width="80px" :model="editForm" :rules="addFormRules">
        <el-form-item :label="dialogText" prop="attr_name">
          <el-input v-model="editForm.attr_name">
          </el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveEditCate">确 定</el-button>
      </span>
    </el-dialog>
  </div>

</template>

<script>
export default {
  data () {
    return {
      // inputVisible: false,
      // inputValue: '',
      editDialogVisible: false,
      editForm: {},
      manyTableData: [],
      onlyTableData: [],

      cateList: [],
      selectedKeys: [],
      activeName: 'many',
      addDialogVisible: false,
      addForm: {
        attr_name: ''
      },
      addFormRules: {
        attr_name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 定义删除属性抽离代码
    async saveTags (row) {
      const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`,
        { attr_name: row.attr_name, attr_sel: this.activeName, attr_vals: row.attr_vals.join(' ') })
      if (res.meta.status !== 200) return this.$message.error('更新失败')

      this.$message.success('更新成功')
      row.inputValue = ''
      row.inputVisible = false
    },
    // 删除tag属性
    handleRemove (row, index) {
      row.attr_vals.splice(index, 1)
      this.saveTags(row)
    },
    async handleInputConfirm (row) {
      if (row.inputValue === '') {
        row.inputVisible = false
        return
      }
      console.log(row.inputValue)
      // 显示在前端页面，tag标签
      row.attr_vals.push(row.inputValue)
      const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`,
        { attr_name: row.attr_name, attr_sel: this.activeName, attr_vals: row.attr_vals.join(' ') })
      if (res.meta.status !== 200) return this.$message.error('更新失败')

      this.$message.success('更新成功')
      row.inputValue = ''
      row.inputVisible = false
      // this.$http.
    },
    // tag里input框事件
    showInput (row) {
      row.inputVisible = true
      this.$nextTick(() => {
        // console.log(this.$refs.saveTagInput)
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 删除警示框
    removeBox (id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        console.log(id)
        const { data: res } = await this.$http.delete(`categories/${this.cateId}/attributes/${id}`)
        console.log(res)
        if (res.meta.status !== 200) return this.$message.error('删除失败')
        this.getParansList()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 修改属性值逻辑
    saveEditCate () {
      this.$refs.editFormRef.validate(async bool => {
        if (!bool) return this.message.error('修改失败')
        const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${this.editForm.attr_id}`,
          { attr_name: this.editForm.attr_name, attr_sel: this.activeName })
        if (res.meta.status !== 200) return this.$message.error('修改失败')
        this.editDialogVisible = false
        this.getParansList()
      })
    },
    showEditDialog (row) {
      console.log(row)
      this.editForm = { ...row }
      // console.log(this.editForm)
      this.editDialogVisible = true
    },
    // 添加参数和属性逻辑，对应属性弹出框
    addCate () {
      this.$refs.addFormRef.validate(async bool => {
        if (!bool) return this.message.error('添加失败')
        const { data: res } = await this.$http.post(`categories/${this.cateId}/attributes`, { attr_sel: this.activeName, attr_name: this.addForm.attr_name })
        if (res.meta.status !== 201) return this.$message.error('添加失败')
        this.addDialogVisible = false
        this.getParansList()
      })
    },
    handleClose () {
      this.$refs.addFormRef.resetFields()
    },
    // 获取添加提取一个发送axjx代码函数
    async getParansList () {
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, { params: { sel: this.activeName } })
      if (res.meta.status !== 200) return this.$message.error('获取数据错误')
      // 数据二次加工
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        item.inputVisible = false
        item.inputValue = ''
      })
      if (this.activeName === 'many') {
        this.manyTableData = res.data
      } else {
        this.onlyTableData = res.data
      }
      // console.log(res)
    },
    // 动态切换绑定事件
    handleTabClick () {
      console.log(this.activeName)
      this.getParansList()
    },
    // 级联选择器的change属性
    handleChange () {
      // console.log(this.selectedKeys)
      if (this.selectedKeys.length !== 3) {
        // this.selectedKeys = []
        this.selectedKeys = this.manyTableData = this.onlyTableData = []
        return true
      }
      this.getParansList()
    },
    // 获取商品信息
    async getCateList () {
      const { data: res } = await this.$http.get('categories')
      this.cateList = res.data
      // console.log(this.cateList)
    }
  },
  computed: {
    // 添加动态属性，判断数组长度布尔值
    isBtnOk () {
      return this.selectedKeys.length !== 3
    },
    cateId () {
      return this.selectedKeys[this.selectedKeys.length - 1]
    },
    dialogText () {
      // if (this.activeName === 'many') {
      //   return '动态参数'
      // } else {
      //   return '静态属性'
      // }
      return this.activeName === 'only' ? '静态属性' : '动态参数'
    }
  },
  watch: {},
  filters: {},
  components: {},
  created () {
    this.getCateList()
  },
  mounted () { }
}
</script>

<style scoped lang='less'>
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
